<template>
  <div class="fill-width-height app-container" style="overflow: auto">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleDetail">添加图库内图片</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="addLinkImg">添加外部图片链接</el-button></el-col>
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-edit" size="mini" @click="getPageData">刷新</el-button></el-col>
    </el-row>

    <el-tabs v-model="activeType" @tab-click="typeHandleClick">
      <el-tab-pane
        v-for="item in typeList"
        :name="item.id"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-tab-pane>
    </el-tabs>

    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      @expand-change="expandChange"
      border
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column type="expand">
        <template #default="props">
          <el-row :gutter="24" :justify="'left'" style="margin: 10px;">
            <el-col :md="3" :lg="3" :xl="3" :xs="8" :sm="8" v-for="(item, index) in props.row.detailList || []" :key="index" v-if="props.row.cardtype !== 'coll'">
              <img :src="getPreviewPath(item.imgfileid, props.row)" alt="" style="width: 100%;" />
            </el-col>

            <!--   合集  -->
            <el-col :md="3" :lg="3" :xl="3" :xs="8" :sm="8" v-for="(item, index) in props.row.detailList || []" :key="index" v-if="props.row.cardtype === 'coll'" >
              <el-card :body-style="{ padding: '0px' }" shadow="hover" >
                <img :src="getPreviewPath(item.imgfileid, props.row, item)" alt="" style="width: 100%;" />
                <div style="padding: 14px;" >
                  <span>{{item.collname}}</span>
                </div>
              </el-card>
            </el-col>

          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        label="标题"
        prop="title">
      </el-table-column>
      <el-table-column
        label="跳转url"
        prop="clickurl">
      </el-table-column>
      <el-table-column
        label="卡片类型"
        prop="cardtype">
        <template #default="scope">
          <span>{{getDirectionOptionsName(scope.row.cardtype)}}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="是否启用"
        prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="toggleStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="顺序"
        prop="ordernum">
      </el-table-column>

    </el-table>
    <ItemForm :item="itemObj" :mode="mode" ref="itemFormRef" @callBack="() => getPageData()"/>
    <ItemDetail ref="itemDetailRef" :manageId="manageId" :cardtype="cardtype"/>

    <!-- 添加外部图片链接对话框 -->
    <el-dialog
      :visible.sync="linkDialogVisible"
      title="添加外部图片链接"
      @close="handleDialogClose"
    >
      <el-table :data="linkList" style="width: 100%">
        <el-table-column label="图片链接">
          <template #default="scope">
            <el-input v-model="scope.row.link" placeholder="请输入图片链接"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="danger" size="mini" @click="deleteLink(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
     <div style="padding: 10px;">
       <el-button type="primary" @click="addLink">添加链接</el-button>
     </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="linkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveLinks">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {deleteByIds, getPage} from "@/api/imgManage/homeManage";
import { getList, getCollectList, saveList } from '@/api/imgManage/homeManageDetail'
import {directionOptions} from "@/views/imgManage/homeManage/homeHook";
import { getToken } from '@/utils/auth'
import {update} from "@/api/imgManage/homeManage";
import { getList as getTypeList } from "@/api/imgManage/imgType";

export default {
  name: 'homeManage',
  components: {
    ItemForm: () => import('./itemForm'),
    ItemDetail: () => import('./itemDetail')
  },
  data(){
    return {
      cardtype: '',
      tableData: [],
      multipleSelection: [],
      single: true,
      multiple: false,
      mode: 'add',
      itemObj: {
        id: '',
        title: '',
        cardtype: '',
        ordernum: 0
      },
      linkDialogVisible: false, // 控制对话框显示隐藏
      linkList: [], // 存储图片链接的数组
      typeList: [],
      activeType: ''
    }
  },
  computed: {
    manageId(){
      return this.multipleSelection?.length > 0 ? this.multipleSelection[0].id : ''
    }
  },
  methods: {
    typeHandleClick(){
      this.$nextTick(() => {
        this.getPageData()
      })
    },
    async initTypeList() {
      let dataList = await getTypeList({ bustype: "home" }).then(res => res.data)
      if(dataList && dataList[0]){
        this.activeType = dataList[0].id
      }
      this.typeList = dataList
    },
    getPreviewPath(id,row,item){
      if(row.cardtype === 'coll'){
        return this.getImg(item)
      }
      if(id?.startsWith("http")){
        return id
      }
      return this.$config.urlFormat('/openApi/previewByBussId?bussid=' + id)
    },
    getCollectionCoverImg(imgfileid){
      return this.$config.urlFormat(`/openApi/previewCollectionCoverImgById?id=${imgfileid}`)
    },
    getImg(row){
      const Authorization =  "Bearer " + getToken();
      return this.$config.urlFormat(`/file/viewFile?fileName=${row.coverurl}&token=${Authorization}`)
    },
    getDirectionOptionsName(val){
      return directionOptions.find(item => item.value === val)?.label
    },
    handleAdd(){
      this.mode = 'add'
      this.itemObj = {}
      this.$refs.itemFormRef.handleOpen()
    },
    handleUpdate(){
      this.$set(this,'itemObj',this.multipleSelection[0])
      this.mode = 'edit'
      this.$refs.itemFormRef.handleOpen()
    },
    handleDelete(){
      const ids = this.multipleSelection.map(item => item.id)
      this.$modal.confirm('是否确认删除这"' +this.multipleSelection.length + '"条数据？').then(function() {
        return deleteByIds({ids: ids})
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.getPageData()
      }).catch(() => {});
    },
    handleDetail(){
      if(!this.multipleSelection[0]){
        return
      }
      this.cardtype = this.multipleSelection[0].cardtype
      this.$refs.itemDetailRef.open()
    },
    addLinkImg(){
      this.linkDialogVisible = true
      this.linkList = [] // 清空链接列表
    },
    handleSelectionChange(val) {
      if(val.length == 1){
        this.single = false
      }
      if(val.length > 0){
        this.multiple = false
      }
      this.multipleSelection = val;
    },
    toggleStatus(row) {
      const submitObj = Object.assign({}, row);
      update(submitObj).then(res => {
        this.$modal.msgSuccess("状态切换成功");
        this.getPageData();
      }).catch(() => {
        this.$modal.msgError("状态切换失败");
        // 回滚状态
        row.status = row.status === '0' ? '1' : '0';
      });
    },
    expandChange(row){
      // this.$set(row, 'isOpenExpand',!row.isOpenExpand)
      // if(row.isOpenExpand){
      this.getDetailsList(row.id, row)
      // }
    },
    getDetailsList(indexmanageid,row){
      if(row.cardtype === 'coll'){
        getCollectList({ indexmanageid: indexmanageid }).then(res => {
          this.$set(row, 'detailList', res.data)
        })
      } else {
        getList({ indexmanageid: indexmanageid }).then(res => {
          this.$set(row, 'detailList', res.data)
        })
      }

    },
    getPageData(){
      getPage({ hometypeid:  this.activeType }).then(res => {
        res?.rows?.forEach(item => item.detailList = [])
        this.tableData = res.rows
      })
    },
    addLink() {
      this.linkList.push({ link: '' })
    },
    deleteLink(index) {
      this.linkList.splice(index, 1)
    },
    saveLinks() {
      if(this.linkList.length <= 0){
        return this.$modal.msgWarning("请添加数据！")
      }
      console.log('保存的链接列表:', this.linkList.map(item => item.link))
      const linkList = this.linkList.filter(item => item?.link?.length > 0 )
      const submitList = linkList.map((item,index) => {
        return {
          indexmanageid: this.manageId,
          imgfileid: item.link,
          ordernum: index + 1
        }
      })
      saveList(submitList).then(res => {
        this.getPageData()
      })
      this.linkDialogVisible = false
    },
    handleDialogClose() {
      this.linkList = [] // 关闭对话框时清空链接列表
    }
  },
  async mounted() {
    await this.initTypeList()
    this.getPageData()
  }
}
</script>

<style scoped lang="scss">

</style>
